<?php

namespace app\dispatch\controller;

use think\Db;

class Comment
{

    public $count = 1;
    /**
     * 构造函数
     * MfwComment constructor.
     */
    public function __construct(){}

    /**
     *  子进程启动时触发
     * @param $worker
     */
    public function onWorkerStart($worker){
        echo "启动同步派车单状态进程\n";
        if($worker->id === 0 || $worker->id === 1){
            \workerman\Lib\Timer::add(100,[$this, 'syncDispatch']); // 每十五分钟调用一次车调定时任务
        }
    }

    /**
     * 连接时触发
     * @param $connection
     */
    public function onConnect($connection){
        echo "连接成功\n";
        $connection->send('<h2 style="color: #4288ce;font-size: 20px">hello!</h2>');
    }

    /**
     *  接收到消息时触发
     * @param $connection
     * @param $message
     */
    public function onMessage($connection, $message) {
        var_dump($message);
        $connection->send("<span style='color: #000088;'>很高兴和你认识</span>\n");
    }

    /**
     *  连接关闭时触发
     * @param $connection
     */
    public function onClose($connection){
        echo "连接断开了\n";
    }

    /**
     *  worker进程停止时触发
     * @param $connection
     */
    public function onWorkerStop($connection){
        echo "正在重启!\n";
    }

    public function syncDispatch()
    {
        $hour = "5";//设置每日几点同步
        $now_hour = date( "H");//创建当前时间
        if($now_hour == $hour){ //如果当前时间与设置时间相等则进行任务
            try{
                $start_time = mktime(0,0,0,date('m'),date('d'),date('Y'));
                $end_time = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
                $map['go_date'] = array("between",[$start_time,$end_time]);//今天起始与结束的时间戳
                $map['dispatch_group_status'] = 'receiving';//派车单为已接单状态的

                $list = Db::name('dispatch_traveler_group')->where($map)->field('id,dispatch_group_status')->select();

                $update['dispatch_group_status'] = 'proceed';
                $update['driver_confirm'] = true;
                $update['proceed_time'] = NOW_TIME;

                $log = [];
                foreach ($list as $k => $v){
                    //更新状态
                    $res = Db::name('dispatch_traveler_group')
                        ->strict(false)
                        ->where('id', $v['id'])
                        ->update($update);
                    $log[$k]['res'] = $res;
                    $log[$k]['val'] = $v;
                    $log[$k]['update'] = $update;
                }
                logs('syncDispatch',$log);

                echo "同步派车单状态成功\n";
            }catch (\Exception $e){
                echo "同步派车单发生错误：".$e->getMessage()."\n";
            }

        }else{//否则跳过
            echo "OK From syncDispatch\n";
        }
    }

}